﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace DataLayer
{
    /// <summary>
    /// Generic repository that handles communication between service and Database
    /// </summary>
    public class RepositoryBase
    {
        private readonly GameDbEntities _gameDbEntites;

        public RepositoryBase()
        {
            _gameDbEntites = new GameDbEntities();
        }

        public bool Save<TEntity>(TEntity entity)
        {
            var entitySetName = entity.GetType().Name.Replace("Entity", "");
            _gameDbEntites.AddObject(entitySetName, entity);
            var rowsAffected = _gameDbEntites.SaveChanges();

            return (rowsAffected == 1);
        }

        public bool SaveAll<TEntity>(List<TEntity> entities)
        {
            var entitySetName = entities.First().GetType().Name.Replace("Entity", "");
            foreach (var entity in entities)
            {
                _gameDbEntites.AddObject(entitySetName, entity);
            }
            var rowsAffected = _gameDbEntites.SaveChanges();

            return (rowsAffected == entities.Count);
        }

        public bool Delete<TEntity>(TEntity entity)
        {
            _gameDbEntites.DeleteObject(entity);
            var rowsAffected = _gameDbEntites.SaveChanges();

            return (rowsAffected == 1);
        }

        public bool DeleteAll<TEntity>(List<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                _gameDbEntites.DeleteObject(entity);
            }
            var rowsAffected = _gameDbEntites.SaveChanges();

            return (rowsAffected == entities.Count);
        }

        public TEntity GetEntityByID<TEntity>(int id)
        {      
            var entitySetName = typeof(TEntity).Name.Replace("Entity", "");
            var entityKeyValue = new List<KeyValuePair<string, object>>();
            entityKeyValue.Add(new KeyValuePair<string, object>("ID", id));

            var key = new EntityKey(_gameDbEntites.GetType().Name + "." + entitySetName, entityKeyValue);

            return (TEntity)_gameDbEntites.GetObjectByKey(key);            
        }

        public List<TEntity> GetEntitiesWhere<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : class
        {
            var objectSet = _gameDbEntites.CreateObjectSet<TEntity>();
            return objectSet.Where(where).ToList();
        }

        public List<TEntity> GetAll<TEntity>() where TEntity : class
        {
            var objectSet = _gameDbEntites.CreateObjectSet<TEntity>();
            return objectSet.ToList();
        }

        public bool SaveChanges()
        {
            return _gameDbEntites.SaveChanges() > 0 ? true : false;
        }
       
         
    }
}
